<!--
  Gz input 文字上移效果

  @author will
  @site https://pt.jdyd.xyz
  @date 2021/12/10 15:18
-->
<template>
  <div class="gz-text-up table-search-item">
    <a-input
      ref="inputRef"
      :value="value"
      :allowClear="true"
      @change="onChange($event)"
      @focus="focusFunc(true)"
      @blur="focusFunc(false)"
    >
      <template #suffix><slot name="suffix" /></template>
    </a-input>
    <label :class="vdata.labelClass" @click="inputRef.focus()">{{ placeholder }}</label>
  </div>
</template>

<script lang="ts" setup>
import {defineProps, ref, reactive, watch, onMounted} from 'vue'

// 定义input对象
const inputRef = ref()

const vdata = reactive({
  labelClass : {
    'the-lebel': true,
    'the-lebel-up': false,
    'the-lebel-on-input-blur': true
  }
})

// 定义父组件的传参和类型
const props = defineProps({
  value: { type: String, default: null },
  placeholder: { type: String, default: '' },
  isNumber: { type: Boolean, default: false }
})

// 监听属性 
watch( () => props.value ,(newVal)=>{
  vdata.labelClass['the-lebel-up'] = newVal ? true : false
})

onMounted(() => {
  vdata.labelClass['the-lebel-up'] = props.value ? true : false
})

function focusFunc(v){
  vdata.labelClass['the-lebel-on-input-blur'] = !v
}
function extractNumbersFromString(str) {
  const regex = /\d+/g // 匹配一个或多个数字的正则表达式
  const matches = str.match(regex) // 使用正则表达式进行匹配
  const numbers = matches ? matches.join('') : '' // 将匹配到的数字部分连接成一个字符串
  return parseInt(numbers, 10) // 将字符串解析为整数并返回
}
const emit = defineEmits(['update:value'])
const onChange = (e)=> {
  const value = props.isNumber ? extractNumbersFromString(e.target.value) : e.target.value
  emit('update:value', value )
}

</script>

<style scoped lang="less">
// 文字上移 效果
.gz-text-up {
  position: relative;

  input {
    outline: 0;
    transition: all .2s ease;
    height: 34px;
    border-color: #E6E7ED;
  }
  input::-webkit-input-placeholder {
    color: transparent;
    font-size: 13px;
  }
  .the-lebel {
    z-index: 2;
    position: absolute;
    left: 17px;
    bottom: 50%;
    transform: translateY(50%);
    padding: 0px 5px;
    color: #BFBFBF;
    font-size: 13px;
    transition: all .2s ease;
    border-radius: 3px;
    line-height: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: initial;
  }

  .the-lebel-up { // 文字上移效果
    font-weight: normal;
    font-size: 12px;
    letter-spacing: 0.05em;
    text-align: left;
    color: @primary-color;
    background: #fff; // 更换背景色
    transform: translateY(-12px);
  }

  input:focus,input:active{
    border-color: @primary-color;
  }

  .the-lebel-on-input-blur{ // 失去焦点， 需要颜色改为灰色。 
    color: #B0AFB3;
    background: #fff;
  }

}

</style>
